package service

import (
	"common/biz"
	"common/logs"
	"context"
	"core/dao"
	"core/models/db"
	core "core/models/entity"
	"core/repo"
	"encoding/json"
	"fmt"
	"framework/msError"
	"hall/pay/entity"
	"hall/pay/service"
	"strconv"
	"time"
	"user/pb"
)

type PayService struct {
	userDao   *dao.UserDao
	marketDao *dao.MarketDao
	goodsDao  *dao.GoodsDao
	pb.UnimplementedCallbackPayServiceServer
}

func (s *PayService) Register(ctx context.Context, req *pb.CallbackPayParams) (*pb.CallbackPayResponse, error) {
	response, err := service.PostData("hfPayNotify", req)
	if err != nil {
		logs.Error("CallbackPay Register ,err=%v", err)
		return &pb.CallbackPayResponse{}, msError.GrpcError(biz.RequestDataError)
	}
	var returnResAsynchronous entity.ReturnResAsynchronous
	json.Unmarshal([]byte(fmt.Sprintln(response.Data)), &returnResAsynchronous)
	var uidInt int
	if returnResAsynchronous.MerPriv != "" {
		uidInt, _ = strconv.Atoi(returnResAsynchronous.MerPriv[2:])
	} else if returnResAsynchronous.UserId != "" {
		uidInt, _ = strconv.Atoi(returnResAsynchronous.UserId[2:])
	}
	ctx = context.TODO()
	uid := uint(uidInt)
	err = s.userDao.AddHfNotifyLog(ctx, &db.HfNotifyLog{
		UID:        uid,
		Extension:  returnResAsynchronous.Extension,
		UserCustID: returnResAsynchronous.UserCustId,
		OrderID:    returnResAsynchronous.OrderId,
		OrderDate:  returnResAsynchronous.OrderDate,
		Status:     returnResAsynchronous.TransStat,
		DataJson:   response.Data.(string),
	})
	if err != nil {
		return &pb.CallbackPayResponse{}, msError.GrpcError(biz.SqlError)
	}
	//添加记录
	if returnResAsynchronous.Extension == "create_wallet" { //开户
		//创建钱包回调结果处理
		err = s.createWalletNotify(ctx, &db.UserHfWallet{
			UID:        uid,
			UserCustID: returnResAsynchronous.UserCustId,
			AcctID:     returnResAsynchronous.AcctId,
			IDCard:     returnResAsynchronous.UserId,
			UserName:   returnResAsynchronous.UserName,
		})
	} else if returnResAsynchronous.TransStat == "C" { //交易关闭
		switch returnResAsynchronous.Extension {
		case "goods_order": //取消商城交易
			_, _, err = s.goodsDao.GoodsNumAdd(ctx, uid, returnResAsynchronous.OrderId)
			break
		case "trade_order": //取消市场交易
			order := s.marketDao.MongoGetMarketOrderByOrderNo(ctx, uid, returnResAsynchronous.OrderId)
			order.PayStatus = core.TradePayCancel
			order.Cancel = time.Now().Unix()
			err = s.marketDao.MarketOrderCancel(ctx, order)
			break
		}
	} else if returnResAsynchronous.TransStat == "S" { // 成功
		switch returnResAsynchronous.Extension {
		case "wallet_pay": // 开户支付费用
			err = s.walletNotifyPay(ctx, returnResAsynchronous.OrderId, returnResAsynchronous.RespCode)
			break
		case "goods_order": //商城交易
			err = s.goodsNotifyPay(ctx, uid, &returnResAsynchronous, response.Data.(string))
			break
		case "market_order": //市场交易
			err = s.marketNotifyPay(ctx, uid, &returnResAsynchronous, response.Data.(string))
			break
		default:
			err = fmt.Errorf("操作错误")
			break
		}
	}
	if err != nil {
		logs.Error("[CallbackPay] Register ,data=%v,err=%v", returnResAsynchronous, err)
		return &pb.CallbackPayResponse{}, msError.GrpcError(biz.SqlError)
	}
	return &pb.CallbackPayResponse{}, nil
}

func (s *PayService) AliRegister(ctx context.Context, req *pb.AlipayCallbackPayParams) (*pb.AlipayCallbackPayResponse, error) {
	response := req.CheckValue
	logs.Info("%v", response)
	ctx = context.TODO()
	s.goodsDao.MongoNotify(ctx, response)
	return &pb.AlipayCallbackPayResponse{}, nil
}

func (s *PayService) createWalletNotify(ctx context.Context, wallet *db.UserHfWallet) error {
	count := s.userDao.WalletCount(ctx, wallet.UID)
	if count <= 0 {
		return s.userDao.AddWallet(ctx, wallet)
	}
	return nil
}

func (s *PayService) walletNotifyPay(ctx context.Context, orderNo string, respCode string) error {
	if respCode == "C00000" {
		realName := s.userDao.GetReal(ctx, orderNo)
		if realName.UID != 0 {
			return s.userDao.UpRealOsStatus(ctx, realName.UID)
		}
	}
	return nil
}

func (s *PayService) goodsNotifyPay(ctx context.Context, uid uint, request *entity.ReturnResAsynchronous, response string) error {
	if request.RespCode == "C00000" {
		order := s.goodsDao.MongoGetOrderByOrderNo(ctx, uid, request.OrderId)
		if order == nil || order.UID == 0 {
			return fmt.Errorf("goodsNotifyPay 获取数据错误")
		}
		return s.goodsDao.OrderPay(ctx, order, response)
	}
	return nil
}

func (s *PayService) marketNotifyPay(ctx context.Context, uid uint, request *entity.ReturnResAsynchronous, response string) error {
	if request.RespCode == "C00000" {
		order := s.marketDao.MongoGetMarketOrderByOrderNo(ctx, uid, request.OrderId)
		if order == nil || order.UID == 0 {
			return fmt.Errorf("marketNotifyPay 获取数据错误")
		}
		//分账处理
		return s.marketDao.OrderPay(ctx, order, response)
	}
	return nil
}

func NewPayService(manager *repo.Manager) *PayService {
	return &PayService{
		userDao:   dao.NewUserDao(manager),
		marketDao: dao.NewMarketDao(manager),
		goodsDao:  dao.NewGoodsDao(manager),
	}
}
